﻿using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;

namespace TiTi.tea.Comm
{
    public static class Extends
    {
      public static IQueryable<T> SetPage<T,TKey>(this IQueryable<T> souce, Expression<Func<T, TKey>> keySelector, PagePara pagePara)
        {
            pagePara.Total = souce.Count();
            return souce.OrderByDescending(keySelector).Skip(pagePara.GetSkip()).Take(pagePara.PageSize);
        }

        public static bool IsNullOrEmpty(this string str)
        {
            return String.IsNullOrEmpty(str);
        }

        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonItem(this object obj)
        {
            if (obj == null) return "{}";

            try
            {
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                timeConverter.DateTimeFormat = "yyyy-MM-dd hh:mm:ss";

                string jsonStr = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings() { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateFormatString = timeConverter.DateTimeFormat });
                return jsonStr;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T FormJsonTo<T>(this string str)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(str, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception)
            {
                return JsonConvert.DeserializeObject<T>("{\"id\":\"\"}");
            }
        }
    }
}
